package com.ktjiaoyu.crm.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktjiaoyu.crm.config.shiro.MyShiroRealm;
import com.ktjiaoyu.crm.mapper.RoleMapper;
import com.ktjiaoyu.crm.mapper.RoleRightMapper;
import com.ktjiaoyu.crm.pojo.Role;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleRightMapper roleRightMapper;

    @Override
    public Page<Role> selectRolePages(Page page, String roleName) {
        //条件构造器
        QueryWrapper queryWrapper = new QueryWrapper();
        if(roleName != null && !"".equals(roleName)){
            queryWrapper.like("role_name",roleName);
        }
        List roleList = roleMapper.selectRolePages(page, queryWrapper);
        page.setRecords(roleList);
        return page;
    }


    @Override
    public boolean saveRoleAndRight(Role role, String[] rightCodes) {

        //新增或修改角色信息
        boolean b = this.saveOrUpdate(role);

        //如果新增成功角色，则将权限信息也一起存入数据库中
        if(b && role.getRoleId()!=null){
            //第二步：先删除旧的角色权限
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("rf_role_id",role.getRoleId());
            roleRightMapper.delete(updateWrapper);
        }

        //第三步：保存新的角色权限
        boolean roleRightOk = true;
        if(rightCodes!=null && rightCodes.length!=0){
            roleRightOk = roleRightMapper.saveRoleRight(role,rightCodes);
        }

        //清空所有用户权限缓存
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        MyShiroRealm realm = (MyShiroRealm) rsm.getRealms().iterator().next();
        realm.clearAllCachedAuthorizationInfo();

        return b && roleRightOk;
    }

    @Override
    public Role findRoleByUserId(Long usrId) {

        return roleMapper.findRoleByUserId(usrId);
    }
}
